package cn.bb.shop.api;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.Arrays;

public class Server {
    public static void main(String[] args) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        ServerSocket serverSocket = new ServerSocket(8080);
        String requestData = "";

        while(true) {
            Socket socket = serverSocket.accept();

            byte[] buf = new byte[1];

            while (socket.getInputStream().read(buf) != -1) {
                requestData = requestData + new String(buf);
            }
            System.out.println(requestData);
            //解码
            String[] attr = requestData.split("/r/n");
            System.out.println(Arrays.toString(attr));
            String pageName = attr[0];
            String className = attr[1];
            String methodName = attr[2];
            String argsName = attr[3];
            //java反射
       /* 这个一般不用因为我们不能判断参数类型
       Class<?> aClass = Class.forName(pageName + "." + className);
        ShopOrder shopOrder = (ShopOrder)aClass.newInstance();//实例化
        shopOrder.getOrder(argsName);*/
            //反射 传入包名和类名
            Class<?> aClass = Class.forName(pageName + "." + className);
            //通过方法名和参数类型 确定具体的对应方法   因为多态所以准确
            Method method = aClass.getMethod(methodName, String.class);
            //方法被哪个对象来执行呢    执行方法需要传入要执行的实例化后的对象和参数
            String result = (String) method.invoke(aClass.newInstance(), argsName);

            System.out.println("返回给客户端的数据" + result);
            //写给客户端--字符串转为字节数组
            socket.getOutputStream().write(result.getBytes(Charset.forName("UTF-8")));
            //serverSocket.close();
        }

    }
}
